﻿namespace Cloudio.Web.UI.SourceViewer
{
    using System;
    using System.IO;
    using System.Web;
    using Gaia.WebWidgets;

    public class SourceViewer: Panel
    {
        private readonly Label _lblMarkup = new Label { ID = "lblMarkup" };

        private readonly ImageButton _closeBtn = new ImageButton
                                            {
                                                CssClass = "sourceviewer-close",
                                                ImageUrl = "~/media/icons/Close_16_16.gif"
                                            };

        public event EventHandler CloseClicked;

        public SourceViewer(){}

        public SourceViewer(string path)
        {
            _lblMarkup.Text = HttpContext.Current.Server.HtmlEncode(LoadFileContent(GetSourceMapPath(path)));
        }

        protected override void OnInit(EventArgs e)
        {
            //make markup editable
            //Attributes.Add("contenteditable", "true");

            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            _closeBtn.Click += delegate { if (CloseClicked != null) CloseClicked(this, EventArgs.Empty); };

            EnsureChildControls();
            base.OnLoad(e);
        }

        protected override void CreateChildControls()
        {
            Controls.Add(_closeBtn);
            Controls.Add(_lblMarkup);
            base.CreateChildControls();
        }

        private static string GetSourceMapPath(string path)
        {

            return HttpContext.Current.Server.MapPath(path);
        }

        private static string LoadFileContent(string mapPath)
        {
            string result;
            {
                using (var file = File.OpenRead(mapPath))
                {
                    using (var reader = new StreamReader(file, true))
                    {
                        result = reader.ReadToEnd();
                        reader.Close();
                    }
                    file.Close();
                }
            }
            return result;
        }
    }
}